package com.example.demo.story.impl;

import com.example.demo.story.NetStoryServiceAbstract;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author TCJ
 * @create 2023/11/14
 */
public class LingDianStoryServiceImpl extends NetStoryServiceAbstract {
    @Override
    public String getBaseUrl() {
        return "https://www.xlewen3.com";
    }

    @Override
    public String getReadUrl() {
        return getBaseUrl() + "/147/147738/";
    }

    @Override
    public void analysisChapter() {
        buildAnalysisChapter(getReadUrl());
        this.dto.setTitle("测试测试测试");
    }


    private void buildAnalysisChapter(String url) {
        Document html = super.getHtml(url);
        Element list = html.body().getElementById("list");
        assert list != null;
        Elements dl = list.getElementsByTag("dl");
        boolean start =false;
        for (Element element : dl) {
            if ("dt".equals(element.tag().getName())){
                if (element.text().contains("正文")){
                   start = true;
                   continue;
                }
            }
            Elements a = element.getElementsByTag("a");
            System.out.println(a.text());
            super.dto.getChapter().put(a.text(), getBaseUrl() +  a.attr("href"));
        }
        Element listPage = html.getElementsByClass("listpage").get(0);
        Element right = listPage.getElementsByClass("right").get(0);
        String attr = right.getElementsByTag("a").get(0).attr("href");
        if (StringUtil.isBlank(attr)) {
            return;
        }
        buildAnalysisChapter(getBaseUrl() + attr);
    }

    @Override
    public String getContent(String url) {
        StringBuilder sb = new StringBuilder();
        buildContent(sb, url);
        String s = sb.toString();
        String patternString = "第\\d+章 .*?章节错误,点此举报\\(免注册\\),如遇到内容乱码错字顺序乱,请退出阅读模式或畅读模式即可正常。";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(s);
        return matcher.replaceAll("");
    }

    public void buildContent(StringBuilder sb, String url) {
        Document html = super.getHtml(url);
        Element content = html.getElementById("content");
        assert content != null;
        sb.append(content.text());
        Element element = html.getElementsByClass("section-opt m-bottom-opt").get(0);
        Elements aList = element.getElementsByTag("a");
        for (Element a : aList) {
            String text = a.text();
            if ("下一页".equals(text)) {
                buildContent(sb,getBaseUrl()+ a.attr("href"));
            }
        }
    }
}
